package study.javaee.practice.service.impl;

import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import study.javaee.practice.property.EmailProperty;
import study.javaee.practice.service.EmailService;

import javax.annotation.PreDestroy;
import java.util.logging.Logger;

@Service
public class EmailServiceImpl implements EmailService {

    final EmailProperty emailProperty;
    final JavaMailSender mailSender;
    final SimpleMailMessage message;

    @Autowired
    public EmailServiceImpl(EmailProperty emailProperty, JavaMailSender mailSender) {
        this.emailProperty = emailProperty;
        this.mailSender = mailSender;
        message = new SimpleMailMessage();
        message.setFrom(emailProperty.getFrom());
        message.setSubject("验证码");
    }

    @PreDestroy
    public void destroy(){
        Logger.getLogger(this.getClass().getName()).exiting(this.getClass().getName(), "destroy");
    }

    @Override
    public void sendEmail(String destEmail, String content) {
        sendEmail(destEmail, content, null);
    }

    @Override
    public void sendEmail(String destEmail, String content, String subject) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        message.copyTo(mailMessage);
        mailMessage.setTo(destEmail);
        mailMessage.setText(content);
        if(StringUtil.isNullOrEmpty(subject)){
            mailMessage.setSubject(subject);
        }
        mailSender.send(mailMessage);
    }

}
